import 'dart:collection';

import 'package:flutter/material.dart';

class MosRefreshController extends ChangeNotifier {
  Map<String, dynamic> _params = new HashMap();

  bool _isSearch = false;

  Map<String, dynamic> get params => _params;

  bool get isSearch => _isSearch;

  /// 仅更新数据不刷新页面
  bool updateDataOnly = false;

  /// 是添加操作并且刷新
  bool isAddRow = false;

  /// 是删除操作并且刷新
  bool isRemoveRow = false;

  /// 是更新操作
  bool isUpdateRow = false;

  /// 操作的索引
  int operationRowIndex = -1;

  /// 需要操作的数据
  Map<String, dynamic> needOperationRowData = {};

  /// 当前列表全部数据
  List<Map<String, dynamic>> dataSource = [];

  MosRefreshController({Map<String, dynamic> initParams = const {}}) {
    this._params.addAll(initParams);
  }

  resetInitParams(Map<String, dynamic> params) {
    this._params.addAll(params);
  }

  refresh({Map<String, dynamic> params, bool isSearch = false}) {
    this._isSearch = isSearch;
    if (params != null) {
      this._params.addAll(params);
    }
    if (hasListeners) notifyListeners();
  }

  /// 添加行数据
  addRowData({@required int index, @required Map<String, dynamic> rowData, bool updateDataOnly = false}) {
    this.isAddRow = true;
    this.operationRowIndex = index;
    this.updateDataOnly = updateDataOnly;
    this.needOperationRowData.clear();
    this.needOperationRowData.addAll(rowData);
    if (hasListeners) notifyListeners();
  }

  /// 删除行数据
  removeRowData({@required int index, bool updateDataOnly = false}) {
    if (index == -1) return;
    this.isRemoveRow = true;
    this.operationRowIndex = index;
    this.updateDataOnly = updateDataOnly;
    if (hasListeners) notifyListeners();
  }

  /// 更新行数据
  updateRowData({@required int index, @required Map<String, dynamic> rowData, bool updateDataOnly = false}) {
    this.isUpdateRow = true;
    this.operationRowIndex = index;
    this.updateDataOnly = updateDataOnly;
    this.needOperationRowData.clear();
    this.needOperationRowData.addAll(rowData);
    if (hasListeners) refresh();
  }

  /// 设置数据源
  void setDataSource(List<Map<String, dynamic>> data) {
    dataSource.clear();
    dataSource.addAll(data);
  }

  /// 获取数据源
  List<Map<String, dynamic>> getDataSource() {
    return [...dataSource];
  }

  void clearParams() {
    this._params = {};
  }
}
